<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>

      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="Cascadervalue"
            :options="cateList"
            :props="CascaderProps"
            @change="CascaderChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true"
          >添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="handleTagClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 文本输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true"
          >添加属性</el-button>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="handleTagClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 文本输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加窗口 -->
    <el-dialog
      :title="'添加'+paramsTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="paramsTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改窗口 -->
    <el-dialog
      :title="'修改'+paramsTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="paramsTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      CascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      Cascadervalue: [],
      activeName: "many",
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: ""
      },
      editForm: {},
      addFormRules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }]
      },
      editFormRules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        // console.log(res.data);
        this.cateList = res.data;
      }
    },
    async CascaderChange() {
      if (this.Cascadervalue.length !== 3) {
        this.Cascadervalue = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      } else {
        // console.log(this.Cascadervalue);
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: this.activeName }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        } else {
          // 循环遍历res.data,将其从字符串转换成数组
          res.data.forEach(item => {
            // 三元表达式判断：是否为空，为空则赋值为空数组
            item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];

            // 控制文本框和按钮的切换显示
            item.inputVisible = false;
            // tag文本框输入的内容
            item.inputValue = "";
          });
          console.log(res.data);
          if (this.activeName === "many") {
            this.manyTableData = res.data;
          } else if (this.activeName === "only") {
            this.onlyTableData = res.data;
          } else {
            return this.$message.error("参数错误，获取数据异常！");
          }
        }
      }
    },
    handleTabClick() {
      this.CascaderChange();
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    addParams() {
      this.$refs.addFormRef.validate(async valide => {
        if (!valide) {
          return this.$message.error("数据校验失败！");
        } else {
          const { data: res } = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            }
          );
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.addDialogVisible = false;
            this.CascaderChange();
          }
        }
      });
    },
    async showEditDialog(row) {
      this.editDialogVisible = true;
      console.log(row);

      this.editForm.attr_id = row.attr_id;
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_sel: this.activeName
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.editForm = res.data;
      }
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    editParams() {
      this.$refs.editFormRef.validate(async valide => {
        if (!valide) {
          return this.$message.error("表单内容格式不正确！");
        } else {
          const {
            data: res
          } = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
          );
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.editDialogVisible = false;
            this.CascaderChange();
          }
        }
      });
    },
    async deleteParams(row) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除这条数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${row.attr_id}`
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg + "，删除失败！");
        } else {
          this.$message.success(`${this.paramsTitle}${row.attr_name}已被删除`);

          this.CascaderChange();
        }
      }
    },
    // tag文本框失去焦点或者按下Enter键都会触发
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
      } else {
        row.attr_vals.push(row.inputValue.trim());
        row.inputValue = "";
        row.inputVisible = false;

        this.attrValsHandler(row);
      }
    },
    showInput(row) {
      row.inputVisible = true;
      // $nextTick方法的作用：当页面上的元素都被重新渲染完毕之后，
      // 才会执行回调函数里面的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async attrValsHandler(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(",")
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
      }
    },
    handleTagClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.attrValsHandler(row);
    }
  },
  computed: {
    isBtnDisable() {
      if (this.Cascadervalue.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    cateId() {
      if (this.Cascadervalue.length === 3) {
        return this.Cascadervalue[2];
      } else {
        return "";
      }
    },
    paramsTitle() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  }
};
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.input-new-tag {
  width: 120px;
}
</style>